<template>
	<div class="about">
		<h1>{{id ? '编辑' : '新建'}}广告位</h1>
		<el-form label-width="120px" v-on:submit.native.prevent="save">
			<el-form-item label="名称">
        <el-input v-model="model.name">
				</el-input>
      </el-form-item>
			<el-form-item label="广告">
				<el-button size="small" v-on:click="model.items.push({})">
					<i class="el-icon-plus"></i> 添加广告
				</el-button>
				<!-- 具体思路请看HeroEdit.vue -->
				<el-row type="flex" style="flex-wrap: wrap">	
					<el-col :md=12 v-for="(item,i) in model.items" v-bind:key="i">	<!-- items是数组 -->
						<el-form-item label="跳转链接 (URL)">
							<el-input v-model="item.url"></el-input>	<!-- item.url -->
						</el-form-item>
						<el-form-item label="图片" style="margin-top: 0.5rem;">	<!-- 加上外边距 -->
							<el-upload
								class="avatar-uploader"
								:action="uploadUrl"
								:headers="getAuthHeaders()"
								:show-file-list="false"
								:on-success="res => $set(item,'image',res.url) "		
							>    <!-- 看afterUpload ,this.model.avatar = res.url,这里应该写的是item.image = res.url--><!-- 看models/Ad.js item:[ name:{},image:{}] -->
								<img v-if="item.image" :src="item.image" class="avatar">
								<i v-else class="el-icon-plus avatar-uploader-icon"></i>
							</el-upload>
						</el-form-item>
						<el-form-item>
							<el-button size="small" type="danger" 
							@click="model.items.splice(i, 1)"
							>删除</el-button>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form-item>

			<el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
		</el-form>
	</div>
</template>

<script>
/* eslint-disable */
export default {
	data(){
		return {
			model:{
				// 一定要初始化item为数组，不然新建广告会报错（建议看之前的提交记录）
				items: []	
			},
		}
	},
	// 接收id，尽可能与路由解耦
	props:{
		id: {}
	},
	methods:{
		async afterUpload(res){
			// this.model.icon = res.url
			// vue的一个强制赋值的方法，因为进入页面并没图片上传。model.icon == undefined，即使上传图片也不能显示
			this.$set(this.model, 'icon', res.url)
		},
		async save(){
			// console.log(this.id)
      let res
      if (this.id) {
        res = await this.$http.put(`rest/ads/${this.id}`, this.model)
      } else {
        res = await this.$http.post('rest/ads', this.model)
			}
			// const res = await this.$http.post('items', this.model)
			// push要加/ 斜杠，
			this.$router.push('/ads/list')
			this.$message({
        type: 'success',
        message: '保存成功'
      })
		},
		async fetch(){
      const res = await this.$http.get(`rest/ads/${this.id}`)
      this.model = Object.assign({}, this.model, res.data);	//深拷贝 ,models: {items: [ url:.... , image: ..... ]},具体看HeroEdit
		},
	},
	created(){
		// 存在id的情况下才执行fetch事件（编辑）
    this.id && this.fetch()
  }
}
</script>


